<script setup lang="ts">
import { reactive, ref } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import useUserStore from "@/store/UserStore.ts";
import { useRouter,useRoute } from "vue-router";

import { ElMessage } from "element-plus";
import 'element-plus/theme-chalk/el-message.css'

let loginForm = reactive({ username: '', password: '' });
// 按钮加载效果
let loading = ref(false);
// 表单检查的表单对象
const formRef = ref();
// 规则
const rules = reactive({
  username: [
    { required: true, message: 'Please input Activity name', trigger: 'change' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'change' },
  ],
  password: [
    { required: true, message: 'Please input Activity password', trigger: 'change' },
    { min: 3, max: 20, message: 'Length should be 3 to 5', trigger: 'change' },
  ]
});
// store
const userStore = useUserStore();
// 路由
const router = useRouter();
const route = useRoute();
const login = () => {
  formRef.value.validate(async () => {
    loading.value = true;
    try {
      await userStore.login(loginForm);
      loading.value = false;
      const redirect:any = route.query.redirect;
      await router.push({path: redirect || "/"});
      ElMessage({
        message: "登录成功",
        type: "success"
      });
    } catch (e) {
      loading.value = false;
      ElMessage({
        message: (e as Error)?.message,
        type: "error"
      });
    }
  });

}
</script>

<template>
  <div class="loginContainer">
    <el-form
        class="loginForm"
        label-width="80px"
        label="right"
        :rules="rules"
        :model="loginForm"
        ref="formRef"
    >
      <h1>登录</h1>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" :prefix-icon="User" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model = "loginForm.password" :prefix-icon="Lock" show-password />
      </el-form-item>
      <el-form-item>
        <el-button :loading="loading" type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.loginContainer {
  // background-color: #976796;
  background: url("https://img0.baidu.com/it/u=2020518972,2077284106&fm=253&fmt=auto&app=120&f=JPEG?w=889&h=500") no-repeat;
  background-size: cover;
  height: 100vh;
  width: 100%;
  padding: 30vh 45vw;

  .loginForm {
    //position: relative;
    //top: 40vh;
    //left: 50%;
    width: 350px;
    background-color: rgba(255, 255, 255, 0.7);
    padding: 30px 20px 5px;
    border: 0;
    border-radius: 10px;
    h1 {
      margin-bottom: 20px;
    }
  }
}
</style>
